<template>
    <section class="UserSetRoles-container">
        <el-dialog title="设置角色" :visible.sync="isShow" width="42%">
            <div class="content">
                <el-transfer
                    v-model="selectedIds"
                    style="text-align: left; display: inline-block"
                    filterable
                    :data="data"
                    :titles="['全部角色', '已有角色']"
                    :format="{
                        noChecked: '${total}',
                        hasChecked: '${checked}/${total}',
                    }"
                    :button-texts="['移除', '选择']"
                >
                    <span slot-scope="{ option }">{{ option.label }}</span>
                </el-transfer>
            </div>

            <span slot="footer" class="footer">
                <el-button type="primary" :loading="loading" size="medium" @click="doAdd"
                    >确 定</el-button
                >
                <el-button size="medium" plain @click="isShow = false">取 消</el-button>
            </span>
        </el-dialog>
    </section>
</template>

<script>
import role_api from "@/common/api/role";
import user_api from "@/common/api/user";

export default {
    data() {
        return {
            loading: false,
            isShow: false,
            data: [],
            selectedIds: [],
            user_id: -1,
        };
    },
    methods: {
        showDialog(user_id) {
            this.user_id = user_id;
            this.isShow = true;
            this.getAllRoles();
            this.getRoles(user_id);
        },

        async getAllRoles() {
            const result = await role_api.getListAsync({
                page_size: 100,
                page_index: 1,
            });
            this.data = result.data.map((r) => ({
                key: +r.id,
                label: r.name,
            }));

            console.log(this.data);
        },

        async getRoles(user_id) {
            const result = await user_api.getRolesAsync(user_id);
            this.selectedIds = result.data.map((r) => +r.role_id);

            console.log(this.selectedIds);
        },

        async doAdd() {
            await user_api.setRolesAsync(this.user_id, this.selectedIds);
            this.isShow = false;
            this.$message.success({
                message: "设置角色成功",
                type: "success",
            });
        },
    },
    mounted() {},
};
</script>

<style lang="scss" scoped>
.UserSetRoles-container {
    .content {
        display: flex;
        justify-content: center;
        align-items: center;

        margin-bottom: 30px;
    }

    .footer {
        padding: 9px;
    }
}
</style>
